/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BookListFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.kline.bean.BuySellBean;
import io.bhex.app.kline.helper.OrderBookHelper;
import io.bhex.app.kline.presenter.BookListFragmentPresenter;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.WrapContentHeightViewPager;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.quote.bean.DepthDataBean;

/**
 * ================================================
 * 描   述：委托订单
 * ================================================
 */

public class BookListFragment extends BaseFragment<BookListFragmentPresenter, BookListFragmentPresenter.EntrustOrderUI> implements BookListFragmentPresenter.EntrustOrderUI, BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {
    private static final String TAG = "BookListFragment";
    //book默认的列表个数
    private static final int DEFAULT_BOOKLIST_NUM = 20;
    private static final int REFRESH_DATA = 0;
    //    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private EntrustOrderAdapter adapter;
    private float currentDigitNum = 0.0001f;//默认是4位
    private int digitNum=4;
    private CoinPairBean coinPairBean;
    private String symbol;
    private String baseToken;
    private String quoteToken;
    private String exchangeId;
    private String mergeDigitsStr;
    private String basePrecision;
    private String digitStr="0.0001";//默认是4位
    private long lastUpdateTime;
    private Handler mHandler;

    private LinearLayout mLinearLayout;

    private KlineExtActivity klineActivity;

    private OrderBookHelper orderBookHelper = new OrderBookHelper();
    private boolean isShowCumulativeVolume = true;
    private String amountUnit="";

    private WrapContentHeightViewPager vp;

    public BookListFragment() {
    }

    @SuppressLint("ValidFragment")
    public BookListFragment(WrapContentHeightViewPager vp) {
        this.vp = vp;
    }

    @Override
    protected BookListFragmentPresenter.EntrustOrderUI getUI() {
        return this;
    }

    @Override
    protected BookListFragmentPresenter createPresenter() {
        return new BookListFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_book_list_layout, null, false);
        vp.setObjectForPosition(rootView,0);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
//        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initViews() {
        super.initViews();
        klineActivity = (KlineExtActivity) getActivity();
//        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        recyclerView = viewFinder.find(R.id.recyclerView);
        recyclerView.setItemViewCacheSize(50);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);

        mLinearLayout = viewFinder.find(R.id.layout_order);

        Bundle arguments = getArguments();
        if (arguments != null) {
            coinPairBean = (CoinPairBean)arguments.getSerializable(AppData.INTENT.SYMBOLS);
            if (coinPairBean != null) {
                symbol = coinPairBean.getSymbolId();
                baseToken = coinPairBean.getBaseTokenId();
                quoteToken = coinPairBean.getQuoteTokenId();
                exchangeId = coinPairBean.getExchangeId();
                mergeDigitsStr = coinPairBean.getDigitMerge();
                basePrecision = coinPairBean.getBasePrecision();
                digitNum = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(symbol+quoteToken);
            } else {
                DebugLog.w(TAG,"币对参数异常");
            }
        }

        isShowCumulativeVolume = MMKVManager.getInstance().loadBookQuantityShowMode();
        setBookTitles();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case REFRESH_DATA:
                        updateOrderBookList(mitemList,mAverage);
                        break;
                }

            }
        };
    }

    private void setBookTitles() {
        if (coinPairBean != null) {
            amountUnit = klineActivity.baseTokenName;
            viewFinder.textView(R.id.title_buy_amount).setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, amountUnit));
            viewFinder.textView(R.id.title_sell_amount).setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, amountUnit));
            viewFinder.textView(R.id.title_price).setText(String.format(getString(R.string.string_price_ph), klineActivity.quoteTokenName));

            //合约
            if(KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType())||KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())){
                amountUnit = getString(R.string.string_option_unit);
                viewFinder.textView(R.id.title_buy_amount).setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, amountUnit));
                viewFinder.textView(R.id.title_sell_amount).setText(getString(isShowCumulativeVolume ? R.string.string_cumulative_quantity_format : R.string.string_amount_format, amountUnit));
            }
        }
    }


    //设置显示条数
    int defaultListNum = DEFAULT_BOOKLIST_NUM;
    List<BuySellBean> mitemList;
    private float mAverage;
    private void loadData(List<BuySellBean> items, float average) {
        mitemList = items;
        mAverage = average;
        if (mitemList.size() > defaultListNum) {
            mitemList = mitemList.subList(0, DEFAULT_BOOKLIST_NUM);
        } else if (mitemList.size() < defaultListNum) {
            int lackNum = defaultListNum - mitemList.size();
            //填充空数据
            for (int i = 0; i < lackNum; i++) {
                BuySellBean buySellBean = new BuySellBean("", 0, "", 0, 0, 0);
                mitemList.add(buySellBean);
            }
        }


        getActivity().runOnUiThread(()->{
            updateOrderBookList(mitemList,average);
        });

    }

    public interface ShowModeLisenter{
        boolean isShowQuantityMode();
    }

    void updateOrderBookList(List<BuySellBean> items, float average){
        orderBookHelper.updateOrderBookItem(getActivity(),mLinearLayout,mitemList,basePrecision,mAverage,new ShowModeLisenter(){
            @Override
            public boolean isShowQuantityMode() {
                return isShowCumulativeVolume;
            }
        });

    }

    @Override
    protected void addEvent() {
        super.addEvent();

        viewFinder.find(R.id.title_buy_amount).setOnClickListener(this);
        viewFinder.find(R.id.title_sell_amount).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_buy_amount:
            case R.id.title_sell_amount:
                showSelectBookQuantityTypeAlert();
                break;
        }

    }

    private void showSelectBookQuantityTypeAlert() {
        String[] quantityTypeArray = new String[]{getString(R.string.string_cumulative_quantity_format, amountUnit),getString(R.string.string_amount_format, amountUnit)};
        AlertView alertView = new AlertView(null, null, getString(R.string.string_cancel), quantityTypeArray, null, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    isShowCumulativeVolume = true;
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                    setBookTitles();
                }else if(position == 1){
                    isShowCumulativeVolume = false;
                    MMKVManager.getInstance().saveBookQuantityShowMode(isShowCumulativeVolume);
                    setBookTitles();
                }
            }
        });
        alertView.show();
    }

    @Override
    public void onLoadMoreRequested() {
//        swipeRefresh.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                adapter.loadComplete();
//            }
//        }, 500);
    }

//    @Override
//    public void onRefresh() {
//        setRefreshing(false);
//    }
//
//
//    public void setRefreshing(final boolean refreshing) {
//        swipeRefresh.post(new Runnable() {
//            @Override
//            public void run() {
//                swipeRefresh.setRefreshing(refreshing);
//            }
//        });
//    }

    @Override
    public void showDepthView(DepthDataBean data) {
        //LogUtil.d("BookListFragment","showDepthView:"+Thread.currentThread().getName());
        List<BuySellBean> items = new ArrayList<>();
        //阴影比例计算公式：成交金额/[展示买平均值+展示卖平均值）/2]%
        List<List<String>> a = data.getA();
        List<List<String>> resultA;
        if (a.size()>DEFAULT_BOOKLIST_NUM){
            resultA = a.subList(0,DEFAULT_BOOKLIST_NUM);
        }else{
            resultA = a;
        }
        float totalADeal = 0;
        for (List<String> item : resultA) {
            String priceStr = item.get(0);
            String amountStr = item.get(1);

            Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
            Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

//            totalADeal += price * amount;
            totalADeal += amount;

            BuySellBean buySellBean = new BuySellBean();
            buySellBean.sellPrice = priceStr;
            buySellBean.sellAmount = amount;
            buySellBean.dealSell = totalADeal;
            items.add(buySellBean);

        }
        float aV = resultA.size()>0 ? totalADeal / resultA.size() : 0;

        List<List<String>> b = data.getB();
        List<List<String>> resultB;
        if (b.size()>DEFAULT_BOOKLIST_NUM){
            resultB = b.subList(b.size()-DEFAULT_BOOKLIST_NUM,b.size());
        }else{
            resultB = b;
        }
        float totalBDeal = 0;
        int size = items.size();
        for (int i = resultB.size() - 1; i >= 0; i--) {
//        for (int i = 0; i <b.size(); i++) {
            List<String> item = resultB.get(i);
            String priceStr = item.get(0);
            String amountStr = item.get(1);

            Float price = Float.valueOf(TextUtils.isEmpty(priceStr) ? "0" : priceStr);
            Float amount = Float.valueOf(TextUtils.isEmpty(amountStr) ? "0" : amountStr);

            totalBDeal += amount;

            if (resultB.size() - 1 - i < size) {
                BuySellBean buySellBean = items.get(resultB.size() - 1 - i);
                buySellBean.buyPrice = priceStr;
                buySellBean.buyAmount = amount;
                buySellBean.dealBuy = totalBDeal;

            } else {
                BuySellBean buySellBean = new BuySellBean();
                buySellBean.buyPrice = priceStr;
                buySellBean.buyAmount = amount;
                buySellBean.dealBuy = totalBDeal;
                items.add(buySellBean);
            }

        }

        float bV = resultB.size()>0? totalBDeal / resultB.size():0;

//        float average = (aV + bV) / (aV==0||bV==0 ? 1 : 2);
        float average = NumberUtils.sub(totalADeal,totalBDeal)> 0 ? totalADeal : totalBDeal;

        /*getActivity().runOnUiThread(()->{

        });*/
        loadData(items, average);

    }

    @Override
    public void getDepthDataFailed(String msg) {

    }

    @Override
    public float getDigitNum2() {
        return currentDigitNum;
    }


    @Override
    public int getDigitNum() {
        return digitNum;
    }

    @Override
    public String getDigitStr() {
        return digitStr;
    }

//    /**
//     * 设置深度小数位数
//     *
//     * @param event
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(PriceDigitsEvent event) {
//        //设置深度小数位数
//        digitStr = event.digitNum;
//        String strDigits = new BigDecimal(String.valueOf(digitStr)).toPlainString();
//        int startIndex;
//        boolean contains = strDigits.contains(".");
//        if (contains) {
//            startIndex = strDigits.indexOf(".");
//            this.digitNum = strDigits.substring(startIndex + 1, strDigits.length()).length();
//
//        }
//
//        currentDigitNum = TextUtils.isEmpty(digitStr) ? currentDigitNum : Float.valueOf(digitStr);
////        ToastUtils.showShort("小数："+digitNum +"  "+currentDigitNum);
//        getPresenter().mergerData();
//    }



    private class EntrustOrderAdapter extends BaseQuickAdapter<BuySellBean,BaseViewHolder> {

        private float average;

        EntrustOrderAdapter(List<BuySellBean> data, float average) {
            super(R.layout.item_book_list_layout, data);
            this.average = average;
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, final BuySellBean itemModel) {
            int digitOfVolume = NumberUtils.calNumerCount(getActivity(), basePrecision);
            baseViewHolder.setText(R.id.item_amount_buy,TextUtils.isEmpty(itemModel.buyPrice) ? getString(R.string.string_placeholder) : io.bhex.baselib.utils.NumberUtils.handVolumeLength(itemModel.buyAmount+"",digitOfVolume));
            baseViewHolder.setText(R.id.item_amount_sell,TextUtils.isEmpty(itemModel.sellPrice) ? getString(R.string.string_placeholder) : io.bhex.baselib.utils.NumberUtils.handVolumeLength(itemModel.sellAmount+"",digitOfVolume));
            baseViewHolder.setText(R.id.item_price_buy, TextUtils.isEmpty(itemModel.buyPrice) ? getString(R.string.string_placeholder) : itemModel.buyPrice);
            baseViewHolder.setText(R.id.item_price_sell, TextUtils.isEmpty(itemModel.sellPrice) ? getString(R.string.string_placeholder) : itemModel.sellPrice);
            float pB = itemModel.dealBuy / average * 100;
            float pS = itemModel.dealSell / average * 100;
            pB = Double.isInfinite(pB) || Double.isNaN(pB) ? 0f : pB;
            pS = Double.isInfinite(pS) || Double.isNaN(pS) ? 0f : pS;
            pB = pB > 100 ? 100 : pB;
            pS = pS > 100 ? 100 : pS;

            baseViewHolder.setProgress(R.id.progress_buy, 100 - new BigDecimal(pB).intValue());
            baseViewHolder.setProgress(R.id.progress_sell, new BigDecimal(pS).intValue());

        }

        public void setAverage(float average) {
            this.average = average;
        }
    }
}
